package com.mk.ribbon.balancer;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoadBalancer {

    AtomicInteger counter = new AtomicInteger(0);

    /**
     * 轮询模式
     * @param instances
     * @return
     */
    public ServiceInstance getInstanceByCycle(List<ServiceInstance> instances){
        int index = counter.incrementAndGet() % 2;
        return instances.get(index);
    }

    /**
     * 随机模式
     * @param instances
     * @return
     */
    public ServiceInstance getInstanceByRandom(List<ServiceInstance> instances){
        int index = new Random().nextInt(instances.size());
        return instances.get(index);
    }
}
